package com.grieous.web.mvc.controller;

import java.io.File;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.grieous.biz.UserBiz;
import com.grieous.domain.PageModel;
import com.grieous.domain.User;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserBiz userBiz;

	@RequestMapping("/user")
	public String search(Integer page, Integer pageSize,
			HttpServletRequest request) {
		PageModel pageModel = userBiz.getUser(pageSize, page);
		request.setAttribute("pageModel", pageModel);
		return "user/user";
	}

	@RequestMapping("/saveuser")
	public String saveUser(@Valid User user,BindingResult bindResult) {
		if(bindResult.hasErrors()){
			System.out.println("校验错误!!!"+bindResult.getFieldError());
		}else{
			userBiz.saveUser(user);
		}
		return "user/user";
	}

	@RequestMapping("/deluser")
	public String delUser(int[] userIds, HttpServletRequest request) {
		userBiz.delUser(userIds);
		return "user/user";
	}

	@RequestMapping("/userdetail")
	public String userDetail(int id, HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		try {
			PrintWriter pw = response.getWriter();
			User user = userBiz.getUserById(id);
			ObjectMapper map = new ObjectMapper();
			pw.write(map.writeValueAsString(user));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	@RequestMapping("/uploadpage")
	public String updatePage(){
		return "user/uploadpage";
	}
	
	@RequestMapping("/upload")
	public String updateThumb(String name,MultipartFile file)throws Exception{
		if(!file.isEmpty()){
			file.transferTo(new File("d:/temp/"+file.getOriginalFilename()));
			return "redirect:success.htm";
		}else{
			return "redirect:fail.htm";
		}
	}
}
